<?php
/**
 * Created by PhpStorm.
 * 订单模块
 * User: caicm
 * Date: 2017/6/21
 * Time: 14:52
 */

namespace WMApi\Model;


use Think\Model;

class WmOrderInfoModel extends Model {

    
    /**
     * 获取订单信息及支付日志
     * 
     * @param string $order_sn 订单编号;
     * @param string $order_type 支付日志订单类型(0订单支付; 1会员充值; 2外卖订单支付;);
     * 
     * @author ^2_3^
     */
    public function get_order_pay_log( $order_sn, $order_type = PAY_WM_ORDER ) {
        if( empty($order_sn) ) {
            returnApiError('get_order_pay_log() 缺失order_sn;');
        }
        
        $where = array(
            "oi.order_sn" => $order_sn,
            "pl.order_type" => $order_type
        );
        $order_pay_info = $this->alias('oi')
            ->join("sdx_pay_log pl ON pl.order_id = oi.order_id")
            ->where($where)
            ->find();
        
        return $order_pay_info;
    }
    
    /**
     * [客户端]获取用户订单列表
     * 
     * @param int $uid 用户ID;
     * @param string $limit 分页字串;
     * 
     * @author ^2_3^
     */
    public function get_order_list( $uid=0, $limit='' ) {
        if( empty($uid) ) {
            returnApiError('提示:缺少用户参数;');
        }
        
        $where = array(
            "oi.uid" => $uid
        );
        
        $list = $this->alias('oi')->field("
                oi.order_id,
            	oi.order_sn,
            	oi.uid,
            	oi.add_time,
            	oi.pay_fee,
            	oi.order_status,
            	oi.seller_status,
            	oi.tail_end_status,
            	oi.seller_id,
            	oi.store_id,
            	s.store_name,
            	s.store_img,
            	CONCAT(og.goods_name,'等',SUM(og.goods_number), '件商品') AS goods_name_str
            ")
            ->join("sdx_wm_store s ON s.store_id = oi.store_id", "left")
            ->join("sdx_wm_order_goods og ON og.order_id = oi.order_id", "left")
            ->where($where)
            ->limit($limit)
            ->group("oi.order_id")
            ->order("oi.add_time DESC")
            ->select();
// w_log('cyb_log', "get_order_list \r\n ".$this->getLastSql());
        
        return $list;
    }
    
    /**
     * 获取用户订单列表总数
     * 
     * @param int uid 用户ID;
     * 
     * @author ^2_3^
     */
    public function get_order_count( $uid=0 ) {
        if( empty($uid) ){
            returnApiError('提示:缺少用户参数;');
        }
        
        $where = array(
            "uid" => $uid
        );
        
        $count = $this->where($where)->count();
        return $count;
    }
    
    /**
     * [客户端]获取订单详情
     * 
     * @param int order_id 订单ID;
     * @param string order_sn 订单号;
     * 
     * @author ^2_3^
     */
    public function get_order_details_info($order_id=0, $order_sn='') {
        if( empty($order_id) && empty($order_sn) ) {
            returnApiError('提示:缺少参数;');
        }
        
        $where = array();
        if( !empty($order_id) ) {
            $where['oi.order_id'] = $order_id;
        }
        if( !empty($order_sn) ) {
            $where['oi.order_sn'] = $order_sn;
        }

        $order_info = $this->alias('oi')->field('
                oi.order_id,
            	oi.order_sn,
                oi.seller_id,
                oi.store_id,
                oi.uid,
            	oi.order_status,
            	oi.seller_status,
            	oi.tail_end_status,
            	oi.add_time,
                oi.consignee,
            	oi.mobile,
            	oi.address,
            	oi.address_name,
                oi.shipping_expect_time_start,
                oi.shipping_expect_time_end,
                oi.postscript,
                oi.pay_id,
                oi.pay_time,
                oi.goods_amount,
                oi.shipping_fee,
                oi.pay_fee,
                oi.courier_name,
                oi.courier_phone,
            	og.goods_id,
            	og.goods_name,
                og.sku_id,
            	og.goods_price,
            	og.market_price,
            	og.goods_number,
            	og.main_attr_name,
            	og.main_attr_value_name,
            	og.sec_attr_name,
            	og.sec_attr_value_name,
            	g.goods_img
            ')
            ->join("sdx_wm_order_goods og ON og.order_id = oi.order_id", "left")
            ->join("sdx_wm_goods g ON g.goods_id = og.goods_id", "left")
            ->where( $where )
            ->select();
// w_log('cyb_log', "get_order_details_info \r\n ".$this->getLastSql());
        
        return $order_info;
        
    }
    
    /**
     * 用户提交订单
     * 
     * @param array order_data 订单数据;
     * 
     * @author ^2_3^
     */
    public function user_add_order($order_data = array()){
        return $this->data($order_data)->add();
    }

    /**
     * 商家添加订单
     * Created By caicm
     * @param int $seller_id 商家id
     * @param int $store_id 店铺id
     * @param string $order_sn 订单号
     * @param int $goods_number 商品数量
     * @param string $consignee 收货人姓名
     * @param int $mobile 收货人电话
     * @param string $postscript 订单留言
     * @param string $sign_building 地标
     * @param string $address_name 门牌号
     * @param array $address_data 地址数据
     * @param array $expect_time 配送期望时间
     * @param int $shipping_service_fee 配送服务费
     * @param int $goods_amount 商品价格
     * @param int $goods_weight 商品重量
     * @return mixed
     */
    public function seller_add_order($seller_id=0, $store_id=0, $order_sn='', $goods_number=0, $consignee='', $mobile=0, $postscript='', $sign_building='', $address_name='', $address_data=array(), $expect_time=array(), $shipping_service_fee=0, $goods_amount=0, $goods_weight=0){

        $order_data = array(
            'seller_id' => $seller_id,
            'store_id' => $store_id,
            'goods_number' => $goods_number,
            'goods_amount' => $goods_amount,
            'order_weight' => $goods_weight,
            'consignee' => $consignee,
            'mobile' => $mobile,
            'postscript' => $postscript,
            'sign_building' => $sign_building,
            'address_name' => $address_name,
            'shipping_expect_time_start' => $expect_time['shipping_expect_time_start'],
            'shipping_expect_time_end' => $expect_time['shipping_expect_time_end'],
            'shipping_service_fee' => $shipping_service_fee,
            'shipping_service_fee_state' => 0,
            'add_time' => gmtime(),
            'seller_time' => gmtime(),
            'order_sn' => $order_sn,
            'uid' => 0,
            'user_name' => '',
            'seller_status' => 1,
            'order_status' => 1,
            'order_type' =>1,
            'clearing_state' => 1,
            'source' => get_source(),
            'version' => get_version(),

            'province' => $address_data['province'],
            'city' => $address_data['city'],
            'district' => $address_data['district'],
            'province_name' => $address_data['province_name'],
            'city_name' => $address_data['city_name'],
            'district_name' => $address_data['district_name'],
            'address' => $address_data['address'],
            'longitude' => $address_data['longitude'],
            'latitude' => $address_data['latitude']
        );


        return $this->add($order_data);

    }

    /**
     * 修改订单配送服务
     * Created By caicm
     * @param int $order_id 订单id
     * @param int $shipping_service_fee 配送服务费
     * @param int $trunk_line_status 干线状态（1-未出仓，2-已出仓，3-已到站，4-已出站，5-已回站，6-需回仓，7-已离站，8-已回仓）
     * @param int $tail_end_status 末端状态（1-未接单，2-已接单，3-配送中，4已送达）
     * @return bool
     */
    public function update_shipping_service($order_id=0, $shipping_service_fee=0,  $trunk_line_status=0, $tail_end_status=0){
        $where = array(
            'order_id' => $order_id
        );

        $data = array(
            'shipping_service_fee_state' => 1,
            'shipping_service_fee' => $shipping_service_fee,
            'trunk_line_status' => $trunk_line_status,
            'tail_end_status' => $tail_end_status,

        );
        if($trunk_line_status == 0) unset($data['trunk_line_status']);
        if($tail_end_status == 0) unset($data['tail_end_status']);

        return $this->where($where)->data($data)->save();
    }

    /**
     * 修改订单配送状态
     * Created By caicm
     * @param int $order_id 订单id
     * @param array $data
     * @return bool
     */
    public function update_shipping_state($order_id=0, $data=array()){
        $where = array(
            'order_id' => $order_id
        );

        return $this->where($where)->data($data)->save();
    }

    /**
     * 获取订单状态数量
     * Created By caicm
     * @param int $seller_id 商家id
     * @param int $store_id 店铺id
     * @param int $seller_status 商家状态 （0-未接单 1-已接单 2-拒接单 3-取消订单 ）
     * @param int $tail_end_status 末端状态（1-未接单，2-已接单，3-配送中，4已送达）
     * @param int $order_id 订单id
     * @return mixed
     */
    public function find_order_state_count($seller_id=0, $store_id=0, $seller_status=0, $tail_end_status=0, $order_id=0){

        if($seller_status == 1){
            //$seller_status = array('in', '1,3');
            $seller_status = array('eq', 1);
        }
        $where = array(
            'seller_id' => $seller_id,
            'store_id' => $store_id,
            'seller_status' => $seller_status,
            'tail_end_status' => $tail_end_status,
            'order_id' => $order_id,
            'order_status' => 1,
            'is_del' => 0,
        );
        if($order_id==0) unset($where['order_id']);

        return $this->where($where)->count('order_id');

    }

    /**
     * 获取订单详情
     * Created By caicm
     * @param int $seller_id 商家id
     * @param int $store_id 店铺id
     * @param int $seller_status 商家状态 （0-未接单 1-已接单 2-拒接单 3-取消订单 ）
     * @param int $tail_end_status 末端状态（1-未接单，2-已接单，3-配送中，4已送达）
     * @param int $order_id 订单id
     * @return mixed
     */
    public function find_order_info($seller_id=0, $store_id=0, $seller_status=0, $tail_end_status=0, $order_id=0){

        $where = array(
            'seller_id' => $seller_id,
            'store_id' => $store_id,
            'seller_status' => $seller_status,
            'tail_end_status' => $tail_end_status,
            'order_id' => $order_id,
            'order_status' => 1,
            'is_del' => 0,
        );
        if($seller_status == 0) unset($where['seller_status']);
        if($tail_end_status == 0) unset($where['tail_end_status']);
        if($order_id == 0) unset($where['order_id']);

        return $this->where($where)->find();

    }

    /**
     * 获取订单详情-根据订单id
     * Created By caicm
     * @param int $order_id 订单id
     * @param string $order_sn 订单编号
     * @return mixed
     */
    public function find_orderinfo_by_id($order_id=0, $order_sn=''){

        $where = array(
            'order_id' => $order_id,
            'order_sn' => $order_sn,
        );
        if($order_id==0) unset($where['order_id']);
        if($order_sn=='') unset($where['order_sn']);

        return $this->where($where)->find();
    }

    /**
     * 获取订单列表
     * Created By caicm
     * @param int $seller_id 商家id
     * @param int $store_id 店铺id
     * @param int $seller_status 商家状态 （0-未接单 1-已接单 2-拒接单 3-取消订单 ）
     * @param int $tail_end_status 末端状态（1-未接单，2-已接单，3-配送中，4已送达）
     * @param string $limit 分页
     * @return mixed
     */
    public function find_orderlist_by_state($seller_id=0, $store_id=0, $seller_status=0, $tail_end_status=0, $limit=''){

        if($seller_status == 1){
            //$seller_status = array('in', '1,3');
            $seller_status = array('eq', 1);
        }

        $where = array(
            'o.seller_id' => $seller_id,
            'o.store_id' => $store_id,
            'o.seller_status' => $seller_status,
            'o.tail_end_status' => $tail_end_status,
            'o.order_status' => 1,
            'o.is_del' => 0,
        );

        $field = '
                    o.order_id,
                    o.order_sn,
                    st.store_name,
                    o.order_type,
                    o.province_name,
                    o.city_name,
                    o.district_name,
                    o.address,
                    o.address_name,
                    o.sign_building,
                    o.consignee,
                    o.mobile,
                    o.postscript,
                    o.goods_amount,
                    o.goods_number,
                    o.shipping_fee,
                    o.pay_fee,
                    o.add_time,
                    o.pay_time,
                    o.seller_time,
                    o.shipping_confirm_time,
                    o.shipping_time,
                    o.confirm_time,
                    o.shipping_expect_time_start,
                    o.shipping_expect_time_end,
                    o.shipping_service_fee,
                    o.courier_name,
                    o.courier_phone,
                    o.order_weight,
                    o.seller_status';


        return $this->alias('o')
                    ->field($field)
                    ->where($where)
                    ->join('sdx_wm_store as st on o.store_id = st.store_id')
                    ->limit($limit)
                    ->select();

    }

    /**
     * 修改订单商家状态
     * Created By caicm
     * @param int $seller_id 商家id
     * @param int $store_id 当铺id
     * @param int $order_id 订单id
     * @param int $seller_status 商家状态
     * @param int $shipping_service_fee 配送服务费
     * @param int $trunk_line_status 干线状态（1-未出仓，2-已出仓，3-已到站，4-已出站，5-已回站，6-需回仓，7-已离站，8-已回仓）
     * @param int $tail_end_status 末端状态（1-未接单，2-已接单，3-配送中，4已送达）
     * @return bool
     */
    public function update_seller_status($seller_id=0, $store_id=0, $order_id=0, $seller_status=0, $shipping_service_fee=0, $trunk_line_status=0, $tail_end_status=0){

        $where = array(
            'seller_id' => $seller_id,
            'store_id' => $store_id,
            'order_id' => $order_id
        );

        $data = array(
            'seller_status' => $seller_status,
            'seller_time' => gmtime()
        );

        //商家取消配送单，修改 配送服务费状态为已退回
        if($seller_status == 3){
            $data['shipping_service_fee_state'] =2;
        }

        //接待修改-订单配送状态
        if($seller_status == 1){
            $data['shipping_service_fee_state'] = 1;
            $data['shipping_service_fee'] = $shipping_service_fee;
            $data['trunk_line_status'] = $trunk_line_status;
            $data['tail_end_status'] = $tail_end_status;
        }


        return $this->where($where)->data($data)->save();

    }

    /**
     * 获取结算订单列表
     * Created By caicm
     * @return mixed
     */
    public function get_clearing_list(){

        //获取结算时间错
        $confirm_time = local_strtotime(date("Y-m-d",strtotime("-".C('order_clearing_day')." day")));

        $where = array(
            'order_type' => 0,          //订单类型：正常订单
            'order_status' => 1,        //支付状态：已付款
            'seller_status' => 1,       //商家状态：接单
            'tail_end_status' => 4,     //末端状态（1-未接单，2-已接单，3-配送中，4已送达）
            'is_del' => 0,              //删除状态：否
            'clearing_state' => 0,      //结算状态：未结算
            //'confirm_time' => array('lt', $confirm_time),   //结算时间  (测试注释，到正式要打开)
        );

        $field = 'order_id,order_sn,seller_id,store_id,uid,shipping_service_fee,pay_fee';

        return $this->field($field)->where($where)->select();

    }


    /**
     * 修改订单结状态为已结算
     * Created By caicm
     * @param int $order_id 订单id
     * @return bool
     */
    public function update_order_clearing_state($order_id=0){

        $where = array(
            'order_id' => $order_id
        );

        $data = array(
            'shipping_service_fee_state' => 1,
            'clearing_state' => 1,
            'clearing_time' => gmtime(),
        );

        return $this->where($where)->data($data)->save();

    }

    /**
     * 获取未结算余额
     * Created By caicm
     * @param int $seller_id
     * @return mixed
     */
    public function get_unavailable_money($seller_id=0){
        $where = array(
            'clearing_state' => 0,      //结算状态：未结算
            'order_status' => 1,        //订单状态：已付款
            'seller_status' => 1,       //商家状态：已接单
            'tail_end_status' => 4,     //物流状态：已送到
            'order_type' => 0,          //订单类型：用户下单
            'seller_id' => $seller_id
        );


        return $this->where($where)->sum('pay_fee-shipping_service_fee');
    }
}